<?php

//Print any input data received from form posts.
print(print_r($_GET)."</br>");

//Set up the database connection
print("Connecting to DB...</br>");
$con = mysql_connect("localhost","root","");
if (!$con) {
	die('Could not connect: ' . mysql_error());
}
mysql_select_db("jabu_hello_world", $con);

// Selecting the action to perform (add/update/delete)
$action = $_GET['action'];
if ($action == 'add') {
	handleAdd();
} elseif ($action == 'update') {
	handleUpdate();
} elseif ($action == 'delete') {
	handleDelete();
} else {
	//do nothing
}

function handleAdd() {
	print("Adding a person the the database.");

	//Setting up some variables.
	$id = $_GET['id'];
	$name = $_GET['name'];
	$surname = $_GET['surname'];
	$address = $_GET['address'];
	$city = $_GET['city'];

	//Sending SQL command to the databsae.
	$result = mysql_query("INSERT INTO Persons (P_Id, FirstName, LastName, Address, City)
	VALUES ('".$id."', '".$name."', '".$surname."', '".$address."', '".$city."')");
	//Handling a possible database error.
	if (!$result) {
		die('Invalid query: ' . mysql_error());
	}

	//Record should be in the DB now.
}

function handleUpdate() {
	//TODO
}

function handleDelete() {
	print("Deleting a person from the database.");

	//Setting up some variables.
	$id = $_GET['id'];
	
	//Sending SQL command to the databsae.
	$result = mysql_query("DELETE FROM Persons WHERE P_Id=".$id);
	//Handling a possible database error.
	if (!$result) {
		die('Invalid query: ' . mysql_error());
	}

	//Record should be removed from the DB now.
}

//Read all people records from database.
$people = mysql_query("SELECT * FROM Persons");

//Close the DB connection.
mysql_close($con);	

?>

<html>
	<head>
		<title>Person list</title>
	</head>
	<body>
		<h1>Person List</h1>
		<p><a href="add-person.php">Add new person</a></p>
		<table>
			<tr>
				<td>ID</td>
				<td>Name</td>
				<td>Surname</td>
				<td>Address</td>
				<td>City</td>
				<td></td>
			</tr>
			<!-- Create the table rows -->
			<?php
				while($row = mysql_fetch_array($people)) {
					echo "<tr>";
					echo "<td>".$row['P_Id']."</td>";
					echo "<td>".$row['FirstName']."</td>";
					echo "<td>".$row['LastName']."</td>";
					echo "<td>".$row['Address']."</td>";
					echo "<td>".$row['City']."</td>";
					//Add controls to allow the user to edit or delete the record.
					echo "<td><a href='edit-person.php?id=".$row['P_Id']."'>Edit</a> <a href='person-handler.php?action=delete&id=".$row['P_Id']."'>Delete</a></td>";
					echo "</tr>";
				}
			?>
		</table>
	</body>
</html>